<script lang="ts" setup>
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  prefix: {
    type: String,
    default: "",
  },
  rules: {
    type: Array,
    default: () => {
      return [];
    },
  },
  label: {
    type: String,
    default: "设置库存",
  },
});

const emits = defineEmits(["update:modelValue"]),
  formRef = inject("formRef");

const form = ref({
  stype: 1,
  originalStock: 0,
  originalStockTotal: 0,
  stock: 0,
  totalStock: 0,
});

const detail = computed({
  get: () => {
    let update = false;
    if (props.modelValue.stype === null) {
      update = true;
      props.modelValue.stype = 1;
    }

    let detail = Object.assign({}, form.value, props.modelValue);
    let keys = Object.keys(form.value);
    for (let i = 0; i < keys.length; i++) {
      if (props.modelValue[keys[i]] === undefined) {
        update = true;
        break;
      }
    }
    if (update) emits("update:modelValue", detail);

    return detail;
  },
  set: (val) => {
    emits("update:modelValue", val);
  },
});

const validateSpecStockNum = (rule: any, value: any, callback: any) => {
  // 加库存不能超过规格总库存
  if (
    detail.value.stype == 1 &&
    Number(value) > Number(detail.value.specStock || 0)
  ) {
    callback(new Error("新增库存不能超过规格剩余库存"));
  } else if (
    detail.value.stype == 2 &&
    Number(detail.value.originalStock - value) < 0
  ) {
    callback(new Error("库存不能小于0"));
  }
  callback();
};

const changeSType = () => {
  onChange();
  nextTick(() => {
    formRef.value.validateField(`${props.prefix}num`);
  });
};

const onChange = () => {
  // 计算最终库存
  let differentNum = Number(
    `${detail.value.stype == 1 ? `+` : `-`}${detail.value.num || 0}`
  );
  detail.value.stock = detail.value.originalStock + differentNum;
  detail.value.totalStock = detail.value.originalStockTotal + differentNum;

  detail.value = detail.value;
};
</script>
<template>
  <el-form-item style="margin-bottom: 0">
    <div>
      剩余库存：<span class="mark-text">{{ detail.originalStock }}</span
      >件&nbsp;| 总库存：<span class="mark-text">{{
        detail.originalStockTotal
      }}</span
      >件
    </div>
  </el-form-item>
  <el-form-item :label="`${label}:`">
    <el-radio-group v-model="detail.stype" @change="changeSType">
      <el-radio-button :label="1">加库存</el-radio-button>
      <el-radio-button :label="2">减库存</el-radio-button>
    </el-radio-group>
    <el-form-item
      label-width="10px"
      :prop="`${prefix}num`"
      :rules="[
        ...rules,
        { validator: validateSpecStockNum, trigger: 'change' },
      ]"
    >
      <EasyNumberInput
        v-model="detail.num"
        :min="1"
        unit="件"
        :precision="0"
        @change="onChange"
      />
    </el-form-item>
  </el-form-item>
</template>
